package com.bana.fvs.utils;

import com.alibaba.fastjson.JSON;
import com.bana.fvs.code.SystemLogType;
import com.bana.fvs.model.FogArea;
import com.bana.fvs.model.Lamp;
import com.bana.sys.service.LogService;
import com.bana.sys.utils.Token;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 通知雾区方案websocket
 */
@ServerEndpoint(value = "/websocket/lamp")
@Component
public class LampServer {

    /**
     * 客户端集合
     */
    private static CopyOnWriteArraySet<LampServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 发送session
     */
    private Session session;


    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }

    /**
     * 发送到客户端
     * @param json 发送内容
     */
    private void send(String json)  {

        try
        {
            this.session.getBasicRemote().sendText(json);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

    /**
     * 发送到全部客户端
     * @param lamp 雾灯信息
     */
    public static void sendAll(LogService logService, Lamp lamp){

        String log=String.format(
                "端口:%d 控制器标识码：%s 雾灯编号：%d 是否碰撞：%d"
                ,lamp.getKzqdk(),lamp.getKzqbsm(),lamp.getWdbm(),lamp.getHasCrash()
        );
        logService.insertSystemLog(Token.SystemToken,SystemLogType.NoticeFogarea,log,null);
        String json= JSON.toJSONString(lamp);
        for (LampServer server : webSocketSet) {
            server.send(json);
        }
    }
}
